import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import accuracy_score
import matplotlib
def add_channel_dim(X):
    """
    为 2D 数据增加通道维度，使其适配 CNN 输入要求 (batch_size, features) -> (batch_size, features, 1)
    """
    return np.expand_dims(X, axis=-1)
def compare_models(models, model_names, X_tests, y_test):
    """
    比较多个模型的性能并绘制准确率对比图
    """
    test_accuracies = []

    for i, model in enumerate(models):
        X_test_i = X_tests[i]
        if hasattr(model, 'evaluate'):
            result = model.evaluate(X_test_i, y_test, verbose=0)
            # 判断是否为列表形式返回多个指标（如 loss, accuracy）
            if isinstance(result, list):
                acc = result[1]  # 取出 accuracy
            else:
                acc = result     # 单个指标的情况
        else:
            predictions = model.predict(X_test_i)
            acc = accuracy_score(y_test, predictions)

        test_accuracies.append(acc)
        print(f"{model_names[i]} 测试准确率: {acc:.4f}")

    # 绘制准确率对比图
    matplotlib.rcParams['font.family'] = 'sans-serif'
    matplotlib.rcParams['font.sans-serif'] = ['PingFang SC', 'Arial Unicode MS']
    matplotlib.rcParams['axes.unicode_minus'] = False

    plt.bar(model_names, test_accuracies, color=['blue', 'green', 'red'])
    plt.ylabel('测试准确率')
    plt.title('不同模型的准确率对比')
    plt.ylim([0, 1])
    plt.show()
